package com.java2108.hetong.kafka;


import com.alibaba.fastjson.JSON;
import com.java2108.hetong.dto.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TestConsumer {

    @KafkaListener(topics = {"test", "test1"})
    public void consumer(ConsumerRecord<String, String> consumerRecord) {
        String key = consumerRecord.key();
        String msg = consumerRecord.value();
        log.info("key:{},msg:{}", key, msg);
    }

    @KafkaListener(topics = {"userMsg"})
    public void consumerUserMsg(ConsumerRecord<String, String> consumerRecord, Acknowledgment ack) {
        //取消息
        String key = consumerRecord.key();
        String msg = consumerRecord.value();
        log.info("key:{},msg:{}", key, msg);
        //处理业务
        try {
            User user = JSON.parseObject(msg, User.class);
            log.info("新增用户{},成功", user.getUsername());
            //消息确认，解决重复消费的问题
            ack.acknowledge();
        } catch (Exception e) {
            //消息处理异常了，必须nack，否则可能收不到消息了
            ack.nack(100);
        }
    }


}
